package com.hengpeng.msls.service.activity.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.itfinbase.en.RewardRebateStatus;
import com.hengpeng.itfinbase.en.RewardRedPacketStatus;
import com.hengpeng.itfinbase.en.RewardType;
import com.hengpeng.itfinbase.en.RewardUseType;
import com.hengpeng.itfinbase.persist.Activity;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinbase.persist.RewardRebate;
import com.hengpeng.itfinbase.persist.RewardRedpacket;
import com.hengpeng.itfinbase.persist.UserRefer;
import com.hengpeng.itfinbase.persist.WechatMerchant;
import com.hengpeng.msls.service.ServiceFactory;
import com.hengpeng.msls.service.activity.ActivityService;
import com.hengpeng.msls.vo.activity.RewardRedpacketVo;

@Service
@Lazy
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ServiceFactory serviceFactory;

    @Override
    public ServiceResult<List<Activity>> selectActivityPage(int indexPage, int pageSize) {

        DynamicQuery query = new DynamicQuery(Activity.class);
        query.setIsSearchTotalCount(true);
        query.setPageIndex(indexPage);
        query.setPageSize(pageSize);
        QueryResult<Activity> requery = serviceFactory.getPersistService().findWithPage(Activity.class, query);
        ServiceResult<List<Activity>> result = new ServiceResult<List<Activity>>(requery.getResults());
        result.setReturnListSize((int) requery.getTotalCount());
        return result;
    }

    @Override
    public List<Reward> getRewardsByActivityId(Long id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Activity getActivityById() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public WechatMerchant getWechatMerchantByappId(String merchantId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getRegRedpacketTotalAmountByUserNameAndStatus(String userName, RewardRedPacketStatus[] stastus) {
        DynamicQuery query = new DynamicQuery(RewardRedpacket.class);
        query.addProjection(Projections.sum("money", "moneySum"));
        query.setQueryType(QueryType.JDBC);
        if (null != stastus) {
            query.inArray("status", stastus);
        }
        query.eq("username", userName);
        List list = serviceFactory.getPersistService().find(null, query);
        if (null == list || list.isEmpty()) {
            return "0";
        } else {
            return MoneyUtil.convertFenToYuan(Long.parseLong(list.get(0) == null ? "0" : list.get(0) + ""));
        }
    }

    @Override
    public ServiceResult<List<RewardRedpacketVo>> findRewardRedpacket(Long userId, RewardRedPacketStatus status,
            int curPage, int pageSize) {
        DynamicQuery query = new DynamicQuery(RewardRedpacket.class, "a");
        query.createAlias(Reward.class, "b");
        query.eqProperty("a.rewardId", "b.id");
        query.addProjection(Projections.property("a.money"));// 0
        query.addProjection(Projections.property("b.rewardUseType"));// 1
        query.addProjection(Projections.property("b.deadLine"));// 2
        query.addProjection(Projections.property("b.rewardType"));// 3
        query.addProjection(Projections.property("a.status"));// 4
        query.addProjection(Projections.property("a.gettime"));// 5
        query.addProjection(Projections.property("a.endtime"));// 6
        query.addProjection(Projections.property("a.id"));// 7
        // query.inArray(, params)
        if (userId != null) {
            query.eq("a.userId", userId);
        }
        if (status != null) {
            query.eq("a.status", status);
        }
        query.setPageSize(pageSize);
        query.setPageIndex(curPage);
        query.setQueryType(QueryType.JDBC);
        query.setIsSearchTotalCount(Boolean.TRUE);
        query.desc("a.gettime");
        QueryResult result = serviceFactory.getPersistService().findWithPage(null, query);
        ServiceResult<List<RewardRedpacketVo>> serviceResult = new ServiceResult<List<RewardRedpacketVo>>();
        List<RewardRedpacketVo> lists = new ArrayList<RewardRedpacketVo>();
        Long count = result.getTotalCount();
        serviceResult.setReturnListSize(count.intValue());
        if (result != null && result.getResults().size() > 0) {
            List l = result.getResults();
            for (int i = 0; i < l.size(); i++) {
                Object[] obj = (Object[]) l.get(i);
                RewardRedpacketVo vo = new RewardRedpacketVo();
                vo.setMoney(Long.parseLong(String.valueOf(obj[0])));
                vo.setRewardUseType(RewardUseType.valueOf(String.valueOf(obj[1])));
                vo.setDeadLine(Integer.valueOf(String.valueOf(obj[2])));
                vo.setRewardType(RewardType.valueOf(String.valueOf(obj[3])));
                vo.setStatus(RewardRedPacketStatus.valueOf(String.valueOf(obj[4])));
                Date gettime = DateTimeUtil.formatToDate(String.valueOf(obj[5]), "yyyy-MM-dd HH:mm:ss");
                Date endtime = DateTimeUtil.formatToDate(String.valueOf(obj[6]), "yyyy-MM-dd HH:mm:ss");
                vo.setGettime(gettime);
                vo.setEndtime(endtime);
                vo.setId(Long.valueOf(String.valueOf(obj[7])));
                vo.setRid(String.valueOf(obj[7]));
                lists.add(vo);
            }
        }
        serviceResult.setReturnValue(lists);
        return serviceResult;
    }

    @Override
    public ServiceResult<List<RewardRedpacketVo>> findRegRedpacketByStatus(Long userId, int type, int curPage,
            int pageSize) {
        DynamicQuery query = new DynamicQuery(RewardRedpacket.class, "a");
        query.createAlias(Reward.class, "b");
        query.eqProperty("a.rewardId", "b.id");
        query.addProjection(Projections.property("a.money"));// 0
        query.addProjection(Projections.property("b.rewardUseType"));// 1
        query.addProjection(Projections.property("b.deadLine"));// 2
        query.addProjection(Projections.property("b.rewardType"));// 3
        query.addProjection(Projections.property("a.status"));// 4
        query.addProjection(Projections.property("a.gettime"));// 5
        query.addProjection(Projections.property("a.endtime"));// 6
        query.addProjection(Projections.property("a.id"));// 7

        // query.inArray(, params)
        if (userId != null) {
            query.eq("a.userId", userId);
        }

        if (type == 1) {// 注册红包
            String[] params = { "REGISTER_RED", "INVITE_ONE_RED", "INVITE_TWO_RED", "INVITE_THREE_RED" };
            query.inArray("b.rewardType", params);
        } else if (type == 2) {
            query.eq("b.rewardType", "INVEST_RED");
        } else if (type == 3) {
            String[] params = { "SHARE_ONE_RED", "SHARE_TWO_RED", "SHARE_THREE_RED", "SHARE_FOUR_RED",
                    "SHARE_FIVE_RED", "SHARE_SIX_RED" };
            query.inArray("b.rewardType", params);
        }
        /*query.eq("a.status", RewardRedPacketStatus.CANUSE);*/
        query.setPageSize(pageSize);
        query.setPageIndex(curPage);
        query.setQueryType(QueryType.JDBC);
        query.setIsSearchTotalCount(Boolean.TRUE);
        query.desc("a.gettime");
        QueryResult result = serviceFactory.getPersistService().findWithPage(null, query);
        ServiceResult<List<RewardRedpacketVo>> serviceResult = new ServiceResult<List<RewardRedpacketVo>>();
        List<RewardRedpacketVo> lists = new ArrayList<RewardRedpacketVo>();
        Long count = result.getTotalCount();
        serviceResult.setReturnListSize(count.intValue());
        if (result != null && result.getResults().size() > 0) {
            List l = result.getResults();
            for (int i = 0; i < l.size(); i++) {
                Object[] obj = (Object[]) l.get(i);
                RewardRedpacketVo vo = new RewardRedpacketVo();
                vo.setMoney(Long.parseLong(String.valueOf(obj[0])));
                vo.setRewardUseType(RewardUseType.valueOf(String.valueOf(obj[1])));
                vo.setDeadLine(Integer.valueOf(String.valueOf(obj[2])));
                vo.setRewardType(RewardType.valueOf(String.valueOf(obj[3])));
                vo.setStatus(RewardRedPacketStatus.valueOf(String.valueOf(obj[4])));
                Date gettime = DateTimeUtil.formatToDate(String.valueOf(obj[5]), "yyyy-MM-dd HH:mm:ss");
                Date endtime = DateTimeUtil.formatToDate(String.valueOf(obj[6]), "yyyy-MM-dd HH:mm:ss");
                vo.setGettime(gettime);
                vo.setEndtime(endtime);
                vo.setRid(String.valueOf(obj[7]));
                lists.add(vo);
            }
        }
        serviceResult.setReturnValue(lists);
        return serviceResult;
    }

    @Override
    public ServiceResult<List<RewardRebate>> findRewardRebate(Long userId, int curPage, int pageSize) {
        DynamicQuery query = new DynamicQuery(RewardRebate.class);
        if (userId != null) {
            query.eq("userId", userId);
        }
        query.setPageSize(pageSize);
        query.setPageIndex(curPage);
        query.desc(" CASE status WHEN 'UNACTIVE' THEN 4 WHEN 'CANPAY' THEN 3 WHEN 'PAID' THEN 2 WHEN 'ABANDON' THEN 1 END ");
        query.desc("gettime");
        query.setIsSearchTotalCount(Boolean.TRUE);
        query.setQueryType(QueryType.JDBC);
        System.out.println(query.getSqlResult().getSql());
        QueryResult<RewardRebate> result = serviceFactory.getPersistService().findWithPage(RewardRebate.class, query);
        Long count = result.getTotalCount();
        ServiceResult<List<RewardRebate>> serviceResult = new ServiceResult<List<RewardRebate>>();// 设置返回值
        serviceResult.setReturnValue(result.getResults());
        serviceResult.setReturnListSize(count.intValue());
        return serviceResult;
    }

    @Override
    public Long getFirstInviteCount(String recommendCode) {
        Long count = 0L;
        DynamicQuery first = new DynamicQuery(UserRefer.class);
        first.addProjection(Projections.property("count(*)"));
        first.eq("fromCode", recommendCode);
        List<Object> list = serviceFactory.getProtFactory().findObject(null, first);
        count = (Long) list.get(0);
        return count;
    }

    @Override
    public Long getSecondInviteCount(String recommendCode) {
        Long count = 0L;
        DynamicQuery first = new DynamicQuery(UserRefer.class);
        first.addProjection(Projections.property("toCode"));
        first.eq("fromCode", recommendCode);
        DynamicQuery second = new DynamicQuery(UserRefer.class);
        second.addProjection(Projections.property("count(*)"));
        second.in("fromCode", first);
        List<Object> list = serviceFactory.getProtFactory().findObject(null, second);
        count = (Long) list.get(0);
        return count;
    }
    
    @Override
    public Long getThirdInviteCount(String recommendCode) {
        Long count = 0L;
        DynamicQuery first = new DynamicQuery(UserRefer.class);
        first.addProjection(Projections.property("toCode"));
        first.eq("fromCode", recommendCode);
        DynamicQuery second = new DynamicQuery(UserRefer.class);
        second.addProjection(Projections.property("toCode"));
        second.in("fromCode", first);
        DynamicQuery third = new DynamicQuery(UserRefer.class);
        third.addProjection(Projections.property("count(*)"));
        third.in("fromCode", second);
        List<Object> list = serviceFactory.getProtFactory().findObject(null, third);
        count = (Long) list.get(0);
        return count;
    }

    @Override
    public Long getPaidMoney(Long userId) {
        Long money = 0L;
        DynamicQuery query = new DynamicQuery(RewardRebate.class);
        query.addProjection(Projections.sum("money"));
        query.eq("userId", userId);
        query.eq("status", RewardRebateStatus.PAID);
        List<Object> list = serviceFactory.getProtFactory().findObject(null, query);
        if (list.size()>0) {
            money = (Long) list.get(0);
        }
        return money;
    }

    @Override
    public Long getUnpayMoney(Long userId) {
        Long money = 0L;
        RewardRebateStatus[] status = {RewardRebateStatus.UNACTIVE,RewardRebateStatus.CANPAY};
        DynamicQuery query = new DynamicQuery(RewardRebate.class);
        query.addProjection(Projections.sum("money"));
        query.eq("userId", userId);
        query.inArray("status", status);
        List<Object> list = serviceFactory.getProtFactory().findObject(null, query);
        if (list.size()>0) {
            money = (Long) list.get(0);
        }
        return money;
    }

    
}
